package threads.volatiletest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class SNRunnerWithMap
{

	private static int threadsNumber = 15;

	public static void main(String[] args) throws ExecutionException
	{
		
		Map<Integer, String> serialNumbers = new HashMap<Integer, String>();
		
		ExecutorService execService = Executors.newCachedThreadPool();

		List<Future<SNContainer>> results = new ArrayList<Future<SNContainer>>();

		List<SNProvider> tasks = new ArrayList<SNProvider>();

		for (int i = 0; i < threadsNumber; i++)
		{
			tasks.add(new SNProvider());
		}

		//while (true)
		for (int i = 0; i < 30; i++)
					
		{
			try
			{
				results = execService.invokeAll(tasks);

				for (Future<SNContainer> future : results)
				{
					SNContainer container = future.get();

					if (!serialNumbers.containsKey(container.getSerialNumber()))
					{
						serialNumbers.put(container.getSerialNumber(), container.getThreadName());
					}
					else
					{
						System.out.println("Duplicate is " + container.getSerialNumber() + " thread name=" + container.getThreadName());
						
						for (Map.Entry<Integer, String> current : serialNumbers.entrySet())
						{
							if (current.getKey() == container.getSerialNumber())
							{
								System.out.println("Already in map " + current.getKey() + " thread name=" + current.getValue());
							}
						}
						
						//System.out.println("Already in map " + serialNumbers.get(container.getSerialNumber()));
						
						System.exit(0);
					}
				}
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}

		}

	}
	
	
}
